/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
 */

package com.jinhe.tss.cms.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.jinhe.tss.cms.CMSConstants;
import com.jinhe.tss.cms.dao.IArticleDao;
import com.jinhe.tss.cms.dao.IChannelDao;
import com.jinhe.tss.cms.entity.ArticleType;
import com.jinhe.tss.cms.service.IArticleTypeService;
import com.jinhe.tss.core.exception.BusinessException;

/**
 * 负责处理ArticleType相关业务逻辑
 */
public class ArticleTypeService implements IArticleTypeService {

    @Autowired private IArticleDao articleDao;
    @Autowired private IChannelDao channelDao;

    public List<?> getArticleTypes() {
        return articleDao.getEntities("from ArticleType o");
    }
    
    public List<?> getArticleTypeGroups() {
        return articleDao.getEntities("from ArticleType o where o.isGroup = ?", CMSConstants.TRUE);
    }
    
    public ArticleType getArticleType(Long typeId) {
        ArticleType type = (ArticleType) articleDao.getEntity(ArticleType.class, typeId);
        if (type == null) {
            throw new BusinessException("当前文章种类没有找到，可能已被删除！");
        }
        return type;
    }
    
    public ArticleType createArticleType(ArticleType articleType) {
        return (ArticleType) articleDao.createObject(articleType);
    }
    

    public void updateArticleType(ArticleType articleType) {
        articleDao.update(articleType);
    }
    
    public ArticleType deleteArticleType(Long typeId) {
        // 判断是否能够删除文章类型
        List<?> articleList = articleDao.getEntities("from Article o where o.articleTypeId = ?", typeId);
        if (!articleList.isEmpty()) {
            throw new BusinessException("该种类已被文章引用，不能删除！");
        }
        List<?> channelList = channelDao.getEntities("from Channel o where o.articleTypeId =?", typeId);
        if (!channelList.isEmpty()) {
            throw new BusinessException("该种类已被栏目引用，不能删除！");
        }
        
        ArticleType type = getArticleType(typeId);
        articleDao.delete(type);
        
        return type;
    }
 
    public void deleteArticleTypeGroup(Long typeGroupId) {
        ArticleType type = getArticleType(typeGroupId);
        articleDao.delete(type);

        //删除组下的文章类型
        List<?> list = articleDao.getEntities("from ArticleType t where t.parentId = ?", typeGroupId);
        for ( Object temp : list ) {
            ArticleType articleType = (ArticleType) temp;
            deleteArticleType(articleType.getId());
        }
    }
}